<template>
  <KView class="one-auction-detail">
    <page-header title="竞价" @back-click="toBack"></page-header>
    <template v-if="auctionData!==null">
      <auction-countdown :auction="auctionData" @type-change="auctionTypeChange"></auction-countdown>
      <KView class="one-auction-detail-content">
        <KView class="one-auction-detail-goods">
          <KView class="auction-detail-goods-pic">
            <sys-image :src="auctionData.pic" mode="auto" :radius="8"></sys-image>
          </KView>
          <KView class="auction-detail-goods-info">
            <KView class="auction-detail-goods-name ellipsis">{{auctionData.name}}</KView>
            <KView class="auction-detail-goods-sourcePrice">市场价：¥{{auctionData.sourcePrice}}</KView>
          </KView>
          <KView class="auction-detail-goods-price">
            <KView class="auction-detail-goods-data">
              <span class="price-unit">¥</span>
              <span class="price-num">{{auctionData.price}}</span>
            </KView>
            <KView class="auction-detail-goods-pricetext">
              <span v-if="auctionData.type===2">成交价</span>
              <span v-else>当前价</span>
            </KView>
          </KView>
        </KView>

        <KView v-if="auctionData.type===0" class="one-auction-detail-concern">
          <KView v-if="auctionData.isJoin" class="one-auction-detail-btn disabled">已参加竞价，等待开始</KView>
          <KView v-else class="one-auction-detail-btn" @click="toJoin">我要支付1元参加</KView>
          <KView class="one-auction-detail-count flex-central">
            <KView>活动未开始，目前有{{concernCount}}个人关注</KView>
          </KView>
        </KView>
        <template v-else>
          <KView v-if="hasPriceView" class="one-auction-detail-buy">
            <auction-price-view :auction="auctionData" @refresh-record="refreshRecord" @to-join="toJoin" @payment-price="toPaymentPrice">
            </auction-price-view>
          </KView>
          <KView v-if="auctionData.auctionRecordList.length>0" class="one-auction-detail-record" :class="{'is-border':hasPriceView}">
            <auction-record-view :auction="auctionData"></auction-record-view>
          </KView>
        </template>

        <KView class="one-auction-detail-goodsdata">
          <KView class="goods-detail-title">商品详情</KView>
          <KView class="goods-inner-line"></KView>
          <KView>
            <sys-rich-text :text="auctionData.description"></sys-rich-text>
          </KView>
          <KView class="goods-detail-title goods-detail-tip">商品须知</KView>
          <KView class="goods-inner-line"></KView>
          <KView>
            <sys-rich-text :text="auctionData.tip"></sys-rich-text>
          </KView>
        </KView>
      </KView>
    </template>
  </KView>
</template>

<script>
  import SystemUtil from 'utils/systemUtil';
  import repeatRequest from 'mixins/repeatRequest';
  import storeMixins from 'mixins/storeMixins';

  import PageHeader from 'common/pageHeader';
  import SysImage from 'common/sysImage';
  import SysRichText from 'common/sysRichText';
  import AuctionCountdown from './auctionCountdown';
  import AuctionPriceView from './auctionPriceView';
  import AuctionRecordView from './auctionRecordView';

  import GoodsApi from 'services/goodsApi';
  import AuctionApi from 'services/auctionApi';

  export default {
    mixins: [repeatRequest, storeMixins],
    props: {
      hasBack: {
        type: Boolean,
        default: true
      }
    },

    computed: {
      hasPriceView() {
        let auctionData = this.auctionData;
        if (auctionData === null) {
          return false;
        }
        if (auctionData.type === 1) {
          return true;
        }
        if (auctionData.type === 2) {
          let maxRecord = auctionData.maxRecord;
          if (maxRecord === null) {
            return false;
          }
          let user = this.user;
          return maxRecord.unionid === user.unionid;
        }
        return false;
      }
    },

    data() {
      let id = this.$route.params.id;
      return {
        id,
        auctionData: null,
        isMiniprogram: process.env.isMiniprogram,
        concernCount: null
      };
    },

    created() {
      if (SystemUtil.isEmpty(this.id)) {
        this.toBack();
        return;
      }

      SystemUtil.showLoading();
      window.Promise.all([
        this.setAuctionData(),
        this.saveGoodsHistory()
      ]).then(() => {
        return this.initData().then(() => {
          SystemUtil.hideLoading();
        });
      }).catch(() => {
        SystemUtil.hideLoading();
      });
    },

    methods: {
      setAuctionData() {
        return AuctionApi.getAuctionDetail(this.id).then(res => {
          let systemTime = res.systemTime;
          let nowTime = this.$moment().valueOf();
          let rangeTime = 60 * 1000;
          if (!this.$moment(systemTime).isBetween(nowTime - rangeTime, nowTime + rangeTime, 'second', '[]')) {
            SystemUtil.alert('本地时间与服务器时间不同步，请重新设置时间', '提示').then(() => {
              this.toBack();
            }).catch(() => {});
            return [];
          }

          let auctionData = res.auctionData;
          this.auctionData = auctionData;
          return auctionData;
        });
      },

      saveGoodsHistory() {
        return GoodsApi.addGoodsDetailHistory(this.id).then(msg => {
          return msg;
        });
      },

      initData() {
        let auctionData = this.auctionData;
        if (auctionData.type === 0) {
          return this.setConcernCount().then(concernCount => {
            this.concernCountRunning();
            return concernCount;
          });
        } else if (auctionData.type === 1) {
          return this.setAuctionRecord(true).then(recordList => {
            this.auctionRecordRunning();
            return recordList;
          });
        }
        return this.setAuctionRecord(true);
      },

      setConcernCount() {
        return AuctionApi.getConcernCount(this.id).then(concernCount => {
          this.concernCount = concernCount;
          return concernCount;
        });
      },

      concernCountRunning() {
        this.timeoutList[0] = setTimeout(() => {
          if (this.isDestroy) {
            return;
          }
          if (this.auctionData.type !== 0) {
            return;
          }
          this.setConcernCount().then(() => {
            if (this.timeoutList[0] = null || this.auctionData.type !== 0) {
              return;
            }
            this.concernCountRunning();
          });
        }, 3000);
      },

      setAuctionRecord(isInit = false) {
        let auctionData = this.auctionData;
        return AuctionApi.getAuctionRecord(auctionData).then(recordList => {
          auctionData.setAuctionRecordList(recordList, isInit);
          return recordList;
        });
      },

      auctionRecordRunning() {
        this.timeoutList[1] = setTimeout(() => {
          if (this.isDestroy) {
            return;
          }
          let auctionData = this.auctionData;
          if (auctionData.type !== 1) {
            return;
          }
          this.setAuctionRecord().then(() => {
            if (this.timeoutList[1] = null || auctionData.type !== 1) {
              return;
            }
            this.auctionRecordRunning();
          });
        }, 3000);
      },

      auctionTypeChange(type) {
        this.clearTimeoutList();

        let msg = type === 1 ? '开始竞价' : '结束竞价';
        SystemUtil.showLoading(msg);
        this.initData().then(() => {
          SystemUtil.hideLoading();
        }).catch(() => {
          SystemUtil.hideLoading();
        });
      },

      refreshRecord() {
        this.setAuctionRecord();
      },

      toJoin() {
        let auctionData = this.auctionData;
        SystemUtil.showLoading('');
        AuctionApi.toJoinAuction(auctionData, this.location.lnglat).then(data => {
          if (this.isMiniprogram) {
            wx.requestPayment({
              timeStamp: data.timeStamp,
              nonceStr: data.nonceStr,
              package: data.package,
              signType: data.signType,
              paySign: data.paySign,
              success: res => {
                auctionData.isJoin = true;
              }
            });
          }
          SystemUtil.hideLoading();
        }).catch(() => {
          SystemUtil.hideLoading();
        });
      },

      toPaymentPrice() {
        SystemUtil.showLoading('');
        AuctionApi.toPayAuctionGoods(this.auctionData, this.location.lnglat).then(orderId => {
          SystemUtil.hideLoading();
          let url = `/paymentGoods/${orderId}?type=auction`;
          if (this.isMiniprogram) {
            window.open(url);
          }
        }).catch(() => {
          SystemUtil.hideLoading();
        });
      },

      resetAuctionData() {
        this.auctionData.isPay = true;
      },

      toBack() {
        if (!this.isMiniprogram) {
          window.history.back();
          return;
        }

        if (this.hasBack) {
          wx.navigateBack();
        } else {
          this.$emit('to-page', '/oneAuction');
        }
      }
    },

    components: {
      PageHeader,
      SysImage,
      SysRichText,
      AuctionCountdown,
      AuctionPriceView,
      AuctionRecordView
    }
  };

</script>

<style lang="scss">
  .one-auction-detail {
    height: 100%;

    .page-header {
      margin-bottom: formatPx(20);
    }

    .one-auction-detail-content {
      height: calc(100% - #{formatPx(175)});
      padding-bottom: formatPx(20);
      overflow: auto;

      .one-auction-detail-goods {
        padding: formatPx(40) formatPx(30);
        height: formatPx(185);
        box-shadow: 0 formatPx(10) formatPx(10) formatPx(0) rgba(232, 232, 232, 1);

        >div {
          float: left;
          height: 100%;
        }

        .auction-detail-goods-pic {
          height: calc(100% - 2px);
          width: calc(#{formatPx(185)} - 2px);
          border: 1px solid #F0F0F0;
          border-radius: 8px;
          overflow: hidden;
          margin-right: formatPx(35);
        }

        .auction-detail-goods-info {
          width: formatPx(300);
          padding-top: formatPx(20);

          .auction-detail-goods-name {
            color: #2f3135;
            font-size: formatPx(30);
          }

          .auction-detail-goods-sourcePrice {
            margin-top: formatPx(20);
            color: #999999;
            font-size: formatPx(26);
          }
        }

        .auction-detail-goods-price {
          float: right;
          width: formatPx(160);
          padding-top: formatPx(45);

          .auction-detail-goods-data {
            color: #fd5a3a;
            font-weight: bold;
            text-align: center;

            .price-unit {
              font-size: formatPx(32);
              line-height: formatPx(40);
              margin-right: formatPx(5);
            }

            .price-num {
              font-size: formatPx(40);
              line-height: formatPx(40);
            }
          }

          .auction-detail-goods-pricetext {
            margin-top: formatPx(12);
            font-size: formatPx(26);
            color: #999999;
            text-align: center;
          }
        }
      }

      .one-auction-detail-concern {
        width: 100%;
        height: formatPx(250);
        padding-top: formatPx(50);
        display: flex;
        flex-direction: column;

        .one-auction-detail-btn {
          margin-bottom: formatPx(50);
          margin-left: formatPx(30);
          margin-right: formatPx(30);
          height: formatPx(88);
          line-height: formatPx(88);
          background: #fd5a3a;
          color: #ffffff;
          font-size: formatPx(26);
          text-align: center;
          border-radius: formatPx(44);

          &.disabled {
            background: #e0e0e0;
          }
        }

        .one-auction-detail-count {
          flex: 1;
          color: #666666;
          box-shadow: 0 formatPx(-10) formatPx(10) formatPx(0) rgba(232, 232, 232, 1);
        }
      }

      .one-auction-detail-buy {
        padding: formatPx(60) formatPx(30);
        height: formatPx(222);
      }

      .one-auction-detail-record {
        width: 100%;
        margin-top: formatPx(25);
        margin-bottom: formatPx(20);
        max-height: formatPx(450);
        overflow: auto;

        &.is-border {
          box-shadow: 0 formatPx(-10) formatPx(10) formatPx(0) rgba(232, 232, 232, 1);
        }
      }

      .one-auction-detail-goodsdata {
        margin-top: formatPx(40);
        padding: 0 formatPx(30);

        .goods-detail-title {
          border-left: formatPx(10) solid #FD5A3A;
          font-size: formatPx(36);
          padding-left: formatPx(15);
          line-height: formatPx(40);
          height: formatPx(40);
        }

        .goods-inner-line {
          height: 1px;
          background: #DADADA;
          margin: formatPx(30) 0;
        }

        .goods-detail-tip {
          margin-top: formatPx(30);
        }
      }
    }
  }

</style>
